/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.dianlan.util;

/**
 * <b>(CrcUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/11/23
 */
public class CrcUtil {

    // 多项式校验值
    // static int POLYNOMIAL = 0x180D;
    static int POLYNOMIAL = 0xA001;
    // static int POLYNOMIAL = 0x0000a001;

    public static String getCrc(String data) {
        data = data.replace(" ", "");
        int len = data.length();
        if (!(len % 2 == 0)) {
            return "0000";
        }
        int    num  = len / 2;
        byte[] para = new byte[num];
        for (int i = 0; i < num; i++) {
            int value = Integer.valueOf(data.substring(i * 2, 2 * (i + 1)), 16);
            para[i] = (byte) value;
        }
        return getCrc(para);
    }

    /**
     * 计算CRC16校验码
     *
     * @param bytes 字节数组
     *
     * @return {@link String} 校验码
     *
     * @since 1.0
     */
    public static String getCrc(byte[] bytes) {
        // CRC寄存器全为1
        int CRC = 0x0000ffff;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        // 结果转换为16进制
        String result = Integer.toHexString(CRC).toUpperCase();
        if (result.length() != 4) {
            StringBuffer sb = new StringBuffer("0000");
            result = sb.replace(4 - result.length(), 4, result).toString();
        }
        //高位在前地位在后
        //return result.substring(2, 4) + " " + result.substring(0, 2);
        // 交换高低位，低位在前高位在后
        return result.substring(0, 2) + " " + result.substring(2, 4);
    }

    public static String intToHex(int n) {
        StringBuffer s = new StringBuffer();
        String       a;
        char[]       b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        while (n != 0) {
            s = s.append(b[n % 16]);
            n = n / 16;
        }
        a = s.reverse().toString();
        return a;
    }
}